package com.heima.comment.interceptor;

import com.heima.model.user.pojos.ApUser;
import com.heima.utils.thread.AppThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Optional;

@Slf4j
@Component
public class AppTokenInterceptor implements HandlerInterceptor {

    //前置方法
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //得到header中的信息
        String userId = request.getHeader("userId");
        //将userId存入Optional中
        Optional<String> optional = Optional.ofNullable(userId);
        //optional容纳的对象，如果不是null则isPresent()返回true
        if(optional.isPresent()){
            //把用户id存入threadloacl中
            ApUser apUser=new ApUser();
            apUser.setId(Integer.valueOf(userId));
            AppThreadLocalUtil.setUser(apUser);
            log.info("comment微服务：AppTokenInterceptor设置用户信息到threadlocal中..."+AppThreadLocalUtil.getUser().getId());
        }
        return true;
    }

    //相当于最终方法；controller的响应结果也会经过拦截器，此时会执行postHandle方法。
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        log.info("清理threadlocal...");
        AppThreadLocalUtil.clear();
    }
}